<template>
    <!-- 车辆列表 -->
    
    <a-spin :spinning="store.spinning">
        <div id="lineAndPoly">
            <a-tree
                v-model:checkedKeys="checkedKeys"
                v-model:expandedKeys="expandedKeys"
                :show-line="showLine"
                :show-icon="showIcon"
                :defaultExpandAll="true"
                :tree-data="treeList"
                @select="onSelect"
                @check="onCheck"
            >
                <template #title="{ dataRef }">
                    <template v-if="dataRef.iconCls === '0-0-0-1'">
                        <div>multiple line title</div>
                        <div>multiple line title</div>
                    </template>
                    <template v-else>{{ dataRef.title }}</template>
                </template>

                
                <template #icon="{ key, dataRef }">
                    <template v-if="key === '0-0'">
                        <smile-outlined />
                    </template>
                    <template v-else-if="key === '0-0-0'">
                        <smile-outlined />
                    </template>
                    <template v-else>
                        <a-image v-if="dataRef.iconCls == '1'" :src="baseURL + '/webgis/image/parking.png'" :preview="false"/>
                        <a-image v-if="dataRef.iconCls == '0'" :src="baseURL + '/webgis/image/offline.png'" class="drop-shadow" :preview="false"/>
                    </template>
                </template>
            
                <template #switcherIcon="{ dataRef, defaultIcon }">
                    
                    <FileSyncOutlined v-if="dataRef.iconCls == '1'" />
                    <component :is="defaultIcon" v-else />
                </template>
            </a-tree>
        </div>
    </a-spin>
</template>
<script setup>
let baseURL = import.meta.env.MODE == "development" ? 'http://sittest.rybsj.cn': window.location.origin
import { ref, reactive, defineProps, watch, onMounted, watchEffect,nextTick } from 'vue';
import {customborder,customborder3} from '../views/mapBorder'
import {banline1, banline2} from '../views/mapLines'
import surveillance_camera from '../assets/surveillance-camera.gif'
import dayjs from 'dayjs';
import { useStore } from '@/store/store';

import {
	saveItem,
	getItems,
	getItemById,
	updateItem,
	deleteItem,
} from '../dbFence2';
import { api_get } from '../untils/common.js'
import ndList from '../static/localData/ndList.json'
import iw_close1d3gif from '../assets/iw_close1d3.gif'
import onlinetruck from '../assets/onlinetruck.png'
import offlinetruck from '../assets/offlinetruck.png'
const showLine = ref(true);
const showIcon = ref(true);
const store = useStore();
const toggleSpinning = (val) => {
  store.toggleSpinning(val);
};

const props = defineProps({
	overlays: Object, // 地图覆盖物（需要在父级）（当前组件有对它赋值操作）
	updateOverlays: Function,
	updateList: String,
	updateAmenuTopList: Function,
	catMap: Object,
	toogleStepspen: Function,
	updateSteplist: Function,
	updateSteplistWithStartEnd: Function,
});


// watch(() => props.overlays,async (newValue) => {
//     props.overlays.value = newValue
// });
watch(()=>props.updateList,(newValue)=>{
	updateTreeList()
})

//   如果没有固定的假数据， saveItem 它， 因为用在ant数，form的表单数据为默认值

const formDataByDBList = ref(null);
const treeList = ref([]);


const expandedKeys = ref(['dep1174402719']);
const checkedKeys = ref([]);



watch(checkedKeys, (e,a) => {
    console.log('watch(checkedKeys');
});

import vehicleList from '../static/localData/vehicleList.json'
const updateTreeList = async ()=> {
    const response = await api_get('/webgis/applet/getVehicles.action', { cors: true });
    let list = vehicleList.data;  //test
    if (__prd__) list = response.data.data // api
    
    function addKeysToNestedObjects(items) {
        return items.map((item,index) => {  
            let position = {longitude:ndList[index]['LONGITUDE'],latitude:ndList[index]['LATITUDE']}
            const newItem = {
                ...item, key: item.id, 
                title: item.text.replace('&nbsp;&nbsp;&nbsp;&nbsp;',' '),
                ...position};  
            if (Array.isArray(item.children)) {  
                newItem.children = addKeysToNestedObjects(item.children);
            }
            return newItem;  
        });  
    }  
    list = addKeysToNestedObjects(list);
    list.forEach(parentVal => {  
    // 检查parentVal是否有children属性  
        if (Array.isArray(parentVal.children)) {  
            // 遍历children数组  
            parentVal.children.forEach(childVal => {  
                let position = [childVal.longitude, childVal.latitude];  
                // addMarker(position, childVal);  
            });  
        }  
        // 注意：这里没有为parentVal（即顶级元素）调用addMarker  
    });
    treeList.value = list
    
    // formDataByDBList.value.push(...await getItems('govLine'))
    
    console.log(treeList.value, 'treeList');
    
}

let closeImg

onMounted(async () => {
	formDataByDBList.value = await getItems();
	
    // 测试演示使用
    // addPolygon(customborder,'', 7788);
    // addPolygon(customborder3,'', 7789);
    // addPolyline(banline1,'', 8888);
    // addPolyline(banline2,'', 8889);
    
    nextTick( ()=>{
        setTimeout(() => {
            updateTreeList()
            props.updateAmenuTopList()
        }, 500);
    })

    let marker
        
    if (!window.aMapInfoWindow) {
        let div = document.createElement('div')
            div.innerHTML = `
                <div id="InfoWindowContainer" style=" background: #15285bad;border: 1px solid; padding: 10px; border-radius: 9px; font-size: 13px;">
                    
                </div>
                <iframe src="" id="InfoWinVideo" style="display:none;" allow="fullscreen" width="635px" height="560px" frameborder="0"></iframe>
            `

        closeImg = document.createElement('img');
        closeImg.className = `close mapclose`;
        closeImg.src = iw_close1d3gif;
        closeImg.addEventListener('click', () => {
            // 在这里处理关闭事件
            console.log(`Close button clicked`);
            window.aMapInfoWindow.hide()
        });
        div.append(closeImg)

        
        marker = new AMap.InfoWindow({
            isCustom: true,  //使用自定义窗体
            position: [106.653651, 38.099586],
            offset: new AMap.Pixel(16, -45),
            content: div
        });
        window.aMapInfoWindow = marker
        
        props.catMap.add(marker);
        marker.hide()
    }

});
// 获取getItem 数据后对数据处理成ant树数据格式


const onSelect = (selectedKeys, info) => {
	console.log('selected', selectedKeys, info);
    info.checked = info.selected
    onCheck(selectedKeys, info)
};


let startMarker = ref(null),
    endMarker = ref(null)
startMarker.value = new AMap.Marker({
    position: '',
    map: props.catMap,
        icon:baseURL+'/webgis/map/images/track/start.gif',
        offset: new AMap.Pixel(-20, -26),
    label: {
        // content: '起点',
        offset: new AMap.Pixel(-25, 20)
    },
    extData: {
        type1: 'marker'
    }
});
endMarker.value = new AMap.Marker({
    position: '',
        icon:baseURL+'/webgis/map/images/track/end.gif',
        offset: new AMap.Pixel(-20, -26),
    map: props.catMap,
    label: {
        // content: '终点',
        offset: new AMap.Pixel(-25, 20)
    },
    extData: {
        type1: 'marker'
    }
});
setTimeout(() => {
    startMarker.value.hide()
    endMarker.value.hide()
    props.catMap.add([startMarker.value,endMarker.value]);
}, 500);
// 根据选中节点显示或隐藏覆盖物
// 当前添加覆盖物的列表中如果它们的key和复选框数据key一致, 进行显示隐藏
import gpsInfoListForRoute from '../static/localData/gpsInfoListForRoute.json'
import getVehicleDetail from '../static/localData/getVehicleDetail.json'
import getStopEvent from '../static/localData/getStopEvent.json'
import { message } from 'ant-design-vue';

// task:checked为false时起终点去掉,steps关闭
const onCheck = async (checkedKeys, checked) => {
    let checkedEventKey = checked.node.eventKey
    let checkedNode = checked.node
    let isCar = checkedNode.describe !== null // 是企业还是车辆
    if (!isCar) return
    let key = checkedNode.id
    hideOverlays()
    props.updateSteplist([])
    
    if (checked.checked) {
        toggleSpinning(true)
        // 通过id请求到详细数据 
        // checkedNode.id >>> res
        const responseDetail = await api_get('/webgis/applet/getVehicleDetail.action?devIdnos='+ checkedNode.describe, { cors: true });
        let detail = getVehicleDetail.data;  
        if (__prd__||1111) {
            detail = responseDetail.data.data;  
                if (!detail) {
                message.info('该车暂无数据')
                return 
            }
        }
        
        let longitude = detail.lng
        let latitude = detail.lat
        let position = [longitude, latitude]
        let iconUrl = checkedNode.iconCls == '1' ? onlinetruck : offlinetruck
        addMarker({title: checkedNode.title,iconUrl, position, ...checkedNode, key: checkedNode.key+'_car'})
        
        const response = await api_get('/webgis/applet/getVehicleTrace.action?devIdnos=' + checkedNode.describe, { cors: true });
        let traceList = gpsInfoListForRoute.data //test
        // 循环显示多个P点 // 通过id请求停留点们
        let stops = getStopEvent.data.stopEventList
        if (__prd__||1111) {
            traceList = response.data.data.traceList; //api
            stops = response.data.data.pList
        }
        if (stops.length != 0) {
            props.toogleStepspen(true)
        }

        if (traceList.length == 0) {
            message.info('没有轨迹数据')
        }
        if (stops.length == 0) {
            message.info('没有停留点数据')
        }
            
    
        let paths = traceList.map(item => {
            return [item.longitude?item.longitude:item.lng, item.latitude?item.latitude:item.lat]
        })
        window.stopPaths = {paths}
        props.updateSteplistWithStartEnd(traceList)
        
        
        addLine(paths, checkedNode.id)
        if (paths.length > 0) {

            startMarker.value.setPosition(paths[0])
            startMarker.value.show()
            endMarker.value.setPosition(paths[paths.length-1])
            endMarker.value.show()
        }
        if (props.overlays[key]) {
            props.overlays[key].show()
        }
        if (props.overlays[key + '_car']) {
            props.overlays[key + '_car'].show()
        }

        
        stops.map((step, index)=>{
            // step.id = step.gpsId
            if (!step.gpsId) step.gpsId = 'stop_' + index
            // step.title =  index === 0 ? '起点' : index === stops.length - 1 ? '终点' : step.continuedTime
            step.title =  step.continuedTime
            step.description = index === 0 ? step.location : index === stops.length - 1 ? step.location : ''
            if (step.lng) step.longitude = step.lng
            if (step.lat) step.latitude = step.lat
            
            return step
        })
        props.updateSteplist(stops)
        
        stops.forEach(item=>{
            let position = [item.longitude,item.latitude]
            addStopMarker({
                position,
                title:item.continuedTime,
                key: item.gpsId,
                iconUrl:`${baseURL}/webgis/image/stop.png`,
                ...item
            })
            if (props.overlays[item.gpsId]) {
                props.overlays[item.gpsId].show()
            }
        })

        
        let paddings = [380, 200, 200, 300].map(val => val *= .9)
        
        // 车辆图标和当前选中的paths
        let overlay = props.overlays[key+'_car'] ? props.overlays[key+'_car'] : []
        let overlayCur = props.overlays[key] ? props.overlays[key] : []
        if (overlayCur.length!=0) {
            props.catMap.setFitView([overlayCur, overlay], false, paddings)
        }
    } else {
        hideOverlays()
        props.toogleStepspen(false)
    }
    function hideOverlays(){
        Object.keys(props.overlays).forEach(key=>{
            if ((props.overlays[key] && props.overlays[key].getExtData().track)) {
                props.overlays[key].hide()
            }
        })
        startMarker.value.hide()
        endMarker.value.hide()
        // props.overlays[key+'_car'] ? props.overlays[key+'_car'].hide() :""
        // 循环显示多个P点 // 通过id请求停留点们 //后续写入ref 获取并且隐藏
        let stops = getStopEvent.data.stopEventList
        stops.forEach(item=>{
            if (props.overlays[item.gpsId]) {
                props.overlays[item.gpsId].hide()
            }
        })
    }
    if (checked.checked) {
        toggleSpinning(false)
    }
};


let zIndexAddNum = 1

// 地图显示marker点)可点击该点视频查看, 同时列表显示固废列表
// (title, position)
const stopsClick = (position, item) =>{
    window.aMapInfoWindow.setPosition(position)
    document.querySelector('#InfoWindowContainer').style.display = 'block'
    document.querySelector('#InfoWinVideo').style.display = 'none'
    document.querySelector('#InfoWindowContainer').innerHTML = `
    <div>
        <div><span>开始时间：</span>${item.startTime}</div>
        <div><span>结束时间：</span>${item.endTime}</div>
        <div><span>持续时长：</span>${item.continuedTime}</div>
        ${item.location ? '<div><span>停车地址：</span>'+item.location+'</div>': ''}
    </div>
    `
    let samePosition = JSON.parse(JSON.stringify(position))
    samePosition[1] = samePosition[1]
    props.catMap.setCenter([samePosition[0],samePosition[1]],true)
    let paddings = [380, 200, 200, 300].map(val => val *= .9)
    props.catMap.setFitView(window.aMapInfoWindow, false, paddings)
    window.aMapInfoWindow.show()
}

// news!!! 2024年8月25日14:26:28 新思想
function addStopMarker(item) {
    let {title, key, iconUrl, position} = item
    let content = `
        <div><img class="markerlnglat" width="20" height="20" src="${iconUrl}"><span class="markerText kou">${title}</span></div>
    `
    if (!props.overlays[key]) {
        props.overlays[key] = new AMap.Marker({
            // icon: surveillance_camera,
            position: position,
            offset: new AMap.Pixel(-1, -53),
            content:content,
            extData: {
                track: true
            }
        });
        props.catMap.add(props.overlays[key]);
    } else {
        props.overlays[key].setContent(content)
        props.overlays[key].off('click');
    }
    props.overlays[key].on('click', async () => {
        stopsClick(position, item);
    });
    props.overlays[key]['infowindow'] = item
}

// car/run
function addMarker(item) {
    let {title, key, iconUrl, position} = item
    if (!props.overlays[key]) {
        let content = `
            <div><img class="markerlnglat" width="32" height="32" src="${iconUrl}"><span class="markerText kou">${title}</span></div>
        `
        props.overlays[key] = new AMap.Marker({
            // icon: surveillance_camera,
            position: position,
            offset: new AMap.Pixel(-1, -53),
            content:content,
            extData: {
                track: true
            }
        });

        props.overlays[key].on('click', async () => {
        })

        props.catMap.add(props.overlays[key]);
    }
}

function addLine(paths, key) {
    if (!props.overlays[key] && paths.length != 0) {
        
        var polyline = new AMap.Polyline({
            path: paths,
            isOutline: true,
            outlineColor: 'transparent',
            borderWeight: 3,
            strokeColor: "#e52b1d",
            strokeOpacity: 1,
            strokeWeight: 3,
            // 折线样式还支持 'dashed'
            strokeStyle: "solid",
            // strokeStyle是dashed时有效
            strokeDasharray: [5, 5],
            lineJoin: 'round',
            lineCap: 'round',
            extData: {
                track: true
            }
        })
        
        
        props.catMap.add(polyline);
        props.overlays[key] = polyline
    }
}

function addPolyline(path, where = '', key) {
    var polyline = new AMap.Polyline({
        path: path,
        isOutline: true,
        outlineColor: 'transparent',
        borderWeight: 3,
        strokeColor: "#e52b1d",
        strokeOpacity: 1,
        strokeWeight: 3,
        // 折线样式还支持 'dashed'
        strokeStyle: "solid",
        // strokeStyle是dashed时有效
        strokeDasharray: [5, 5],
        lineJoin: 'round',
        lineCap: 'round',
    })
    var text = new AMap.Text({
        text: where + "禁行路线", //标记显示的文本内容
        anchor: "center", //设置文本标记锚点位置
        draggable: true, //是否可拖拽
        cursor: "pointer", //指定鼠标悬停时的鼠标样式。
        angle: -2, //点标记的旋转角度
        style: {
            //设置文本样式，Object 同 css 样式表
            "padding": "0.15rem .35rem",
            "margin-bottom": "1rem",
            "border-radius": "0.25rem",
            "background-color": "rgb(21 40 91 / 58%)",
            "border-width": "0px",
            "text-align": "center",
            "font-size": "12px",
        },


        position: [path[0][0], path[0][1]], //点标记在地图上显示的位置
    });
    polyline.on('mouseover', () => {

        text.setMap(props.catMap);
    })
    polyline.on('mouseout', () => {
        props.catMap.remove(text)
    })
    props.catMap.add(polyline);
    props.overlays[key] = polyline
    DBAddItem(key, key, path, 'govLine')
    // props.catMap.setFitView();
}

function addPolygon(path, where='', key) {
    // 使用map和forEach来遍历并修改每个坐标  
    path = path.map(coordinates => {  
        return coordinates.map(coordinate => parseFloat((coordinate*1).toFixed(6)));  
    });  
    let layData = {
        path: path,
        fillColor: 'darkred',
        strokeOpacity: 1,
        fillOpacity: 0.5,
        strokeColor: 'blue',
        strokeWeight: 1,
        strokeStyle: 'dashed',
        strokeDasharray: [5, 5],
        zIndex: 50 + zIndexAddNum,
    }
    if (key == 7789) {
        layData = {strokeColor: '#FF33FF',
        strokeWeight: 2,
        fillOpacity: .3,
        fillColor: '#1791fc',
        zIndex:49}
        layData.path = path
    }

    let polygon
    if (!props.overlays[key]) {
        polygon = new AMap.Polygon(layData);
    } else {
        polygon = props.overlays[key]
    }
    
    zIndexAddNum++
    //   text.setMap(catMap); //将文本标记设置到地图上
    let bounds = polygon.getBounds()
    let lng = bounds['northEast']?bounds['northEast'].lng:bounds['northeast']?bounds['northeast'].lng:''
    let lat = bounds['northEast']?bounds['northEast'].lat:bounds['northeast']?bounds['northeast'].lat:''
    var text = new AMap.Text({
        text: where + "禁行区域", //标记显示的文本内容
        anchor: "center", //设置文本标记锚点位置
        draggable: true, //是否可拖拽
        cursor: "pointer", //指定鼠标悬停时的鼠标样式。
        angle: -2, //点标记的旋转角度
        style: {
            //设置文本样式，Object 同 css 样式表
            "padding": "0.15rem .35rem",
            "margin-bottom": "1rem",
            "border-radius": "0.25rem",
            "background-color": "rgb(21 40 91 / 58%)",
            "border-width": "0px",
            "text-align": "center",
            "font-size": "12px",
        },
        
        position: [lng, lat], //点标记在地图上显示的位置
    });
    
    if (key != 7789) {

        polygon.on('mouseover', () => {
            text.setMap(props.catMap);
            polygon.setOptions({
                fillOpacity: 0.7,
                fillColor: 'blue'
            })
        })
        polygon.on('mouseout', () => {
            props.catMap.remove(text)
            polygon.setOptions({
                fillOpacity: 0.5,
                fillColor: 'red'

            })
        })
    }
    if (!props.overlays[key]) {
        props.overlays[key] = polygon
        props.catMap.add(polygon);
        let areaName = key
        if (key == 7789) {
            areaName ='宁东镇'
        }
        DBAddItem(areaName, key, path, 'govArea')
    } else {
        polygon.show()
    }

}


async function DBAddItem(name, key, path, areaType){
    if (Array.isArray(path)) {
        path = path.join(';')
    }
    let FormData = {
        name,
        key,
        id: key,
        userName: '管理员',
        byShare: true,
        byDependency: true,
        bymanor: true,
        byTime: true,
        limitSpeed: true,
        originGpsCoord: true,
        areaType,
        maxSpeed: "90.0",
        startDate: '',
        endDate: '',
        epidemicRisk: '低风险',
        delay: 10,
        glv: 20,
        date: [
            dayjs().startOf('month'),
            dayjs()
        ],
        adname: '',
        txnr: '',
        points: path,
        alarmTypes1s: '',
        alarmTypes2s: '',
        alarmType: '',
        type: '',
        checkedList1: ['进区域报警给驾驶员', '进区域报警给平台'],
        checkedList2: ['进区域报警给驾驶员', '进区域报警给平台'],
        approver: '',
        dateTime: null,
        description: '',
    }
    
    var formInitData = reactive(FormData);
    let rs = await getItemById(areaType, key)
    if (!rs) {
        await saveItem(areaType, formInitData)
    }
}

defineExpose({
    stopsClick
})
</script>
<style>
/* .ant-tree-switcher-line-icon {
    display: none;
} */
.ant-tree-switcher-noop span svg {
    display: none;
}
.ant-tree-switcher-noop  {
    display: flex;
    align-items: center;
}
.ant-tree-switcher-noop span {
    width: 20px;
    height: 20px;
    background: url(../assets/treeicon.png);
    background-size: cover;
    background-size: 16px 16px;
    background-position: bottom;
    background-repeat: no-repeat;
}
.ant-tree-switcher-noop span::after {
    content:'1',
}

.ant-steps.ant-steps-navigation .ant-steps-item-container {
    align-content: center;
}

#lineAndPoly .ant-tree-checkbox:not(.ant-tree-checkbox-disabled) .ant-tree-checkbox-inner {
	background-color: transparent;
	opacity: 0.65;
}

.ant-tree .ant-tree-checkbox:not(.ant-tree-checkbox-disabled) .ant-tree-checkbox-inner {
	border-color: #d9d9d98a;
}

.mapclose {
  position: absolute;
  width: 14px;
  height: 14px;
  cursor: pointer;
  z-index: 99;
  right: -14px;
  top: -8px;
}

.ant-tabs .ant-tabs-tabpane {
    overflow: auto;
}
.ant-tree .ant-tree-switcher-noop {
    visibility: hidden;
    width: 10px;
}
.drop-shadow {
    filter: drop-shadow(0px 0px 1px rgb(255, 255, 255));
}
.ant-tree .ant-tree-node-content-wrapper .ant-tree-iconEle {
    margin-right: 4px;
}
</style>
